<template>
  <el-dialog
      v-loading="loading"
      title="请选择用户角色"
      show-close
      width="50%"
      v-model="dialogVisible"
      :before-close="handleClose"
      append-to-body>
    <el-input
        placeholder="输入关键字进行过滤"
        v-model="filterText">
    </el-input>
    <el-tree :key="roleKey"
             class="filter-tree"
             :data="sourceRoles"
             show-checkbox
             node-key="id"
             :props="defaultProps"
             :default-checked-keys="defaultCheckedKeys"
             default-expand-all
             :filter-node-method="filterNode"
             ref="tree">
    </el-tree>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </template>

  </el-dialog>
</template>

<script>
import {getUserRoles, saveUserRoles} from "@/api/user";
import treeUtils from "@/utils/treeUtils";

export default {
  name: "SelectUserRoles",
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  computed: {
    defaultProps() {
      return {
        children: 'children',
        label: 'roleName',
        value: 'id'
      }
    }
  },
  data() {
    return {
      filterText: "",
      dialogVisible: false,
      sourceRoles: [],
      targetRoles: [],
      defaultCheckedKeys: [],
      userId: null,
      loading: false,
      roleKey: Math.random(),
    }
  },
  created() {
    this.loadSourceRoles();
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true;
      return data[this.defaultProps.label].indexOf(value) !== -1;
    },
    show(userId) {
      if (!userId) return
      this.dialogVisible = true;
      this.userId = userId;
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys([]);
        this.loadTargetRoles()
      })

    },
    loadSourceRoles() {
      getUserRoles().then(res => {
        let data = res.data.data;
        this.sourceRoles = treeUtils.listToTree(data);
      })
    },
    loadTargetRoles() {
      if (!this.userId) return
      this.loading = true
      getUserRoles(this.userId).then(res => {
        let data = res.data.data;
        let temp = [];
        for (let i = 0; i < data.length; i++) {
          temp.push(data[i].id)
        }

        this.defaultCheckedKeys = temp;
        this.roleKey = Math.random();
      }).finally(() => this.loading = false)
    },
    handleClose() {
      this.dialogVisible = false
      this.targetRoles = [];
    },

    submit() {
      let keys = this.$refs.tree.getCheckedKeys();
      saveUserRoles(this.userId, keys).then(res => {
        this.handleClose()
      })
    }
  },

}
</script>

<style scoped>

</style>
